package com.supergzt.interceptor;

import com.supergzt.context.SecurityContextHolder;
import com.supergzt.entity.base.LoginUser;
import com.supergzt.service.TokenService;
import com.supergzt.utils.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 张钧
 * @Description
 * @create 2022-09-25 10:03
 */
@Component
public class HeaderInterceptor implements AsyncHandlerInterceptor {

	@Resource
	private TokenService tokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//若是静态资源就放行，因为静态资源的处理器不是方法处理器
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		//获取jwt token
		String token = SecurityUtils.getToken(request);
		if (token != null) {
			LoginUser loginUser = tokenService.getLoginUser(token);
			if (loginUser != null) {
				tokenService.verifyToken(loginUser);
				SecurityContextHolder.setLoginUser(loginUser);
				SecurityContextHolder.setUserId(loginUser.getUser().getUserId());
				SecurityContextHolder.setUserName(loginUser.getUser().getName());
				SecurityContextHolder.setUserKey(loginUser.getToken());
			}
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		SecurityContextHolder.remove();
	}
}
